package com.gzw.dms.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.gzw.dms.MyApplication;
import com.gzw.dms.R;
import com.gzw.dms.adapter.DriverAdapter;
import com.gzw.dms.adapter.FPOrderAdapter;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.bean.DriverInfo;
import com.gzw.dms.bean.EquipmentInfo;
import com.gzw.dms.bean.ShippingOrderInfo;
import com.gzw.dms.bean.UserInfo;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.UrlUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/3/8.
 */
public class SelectDriverActivity extends BaseActivity{
    private ListView lv_driver;
    private Context mContext;
    private ProgressDialog mProgressDialog;
    private Toolbar toolbar;
    private ArrayList<String> ls_map;
    private Intent mIntetn;
    private ArrayList<DriverInfo> driverInfo;
    private  String driver_id;
    private  String username;
    private  String driverName;
    private String row = "0";
    private String page  = "50";
    private String driver_name ="";
    private String driver_suppliers ="";
    private String driver_phone="";
    private String driver_address = "";
    private String type = "0";
    private String shiping_order_num = "";
    private String shiping_order_goid = "";
    private SwipeRefreshLayout mSwipeLayout;
    private int refresh = 0;

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_selectdriver);
    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        lv_driver = (ListView) findViewById(R.id.lv_driver);
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.id_swipe_ly);

    }

    @Override
    protected void initData() {
        mContext = this;
        toolbar.setTitle("选择司机");
        setSupportActionBar(toolbar);
        mIntetn=getIntent();
        type=(String)mIntetn.getExtras().get("type");
//        ls_map=mIntetn.getStringArrayListExtra("ls_map");
        setSupportActionBar(toolbar);
        ShowOrderTask showOrderTask = new ShowOrderTask();
        showOrderTask.execute(row,page,driver_name,driver_phone,driver_suppliers,driver_address,shiping_order_num,shiping_order_goid);
    }

    @Override
    protected void initEvents() {
        lv_driver.setOnItemClickListener(new mOnItemClick());
        toolbar.setNavigationOnClickListener(new mOnClick());
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh = 1;
                ShowOrderTask showOrderTask = new ShowOrderTask();
                showOrderTask.execute(row,page,driver_name,driver_phone,driver_suppliers,driver_address,shiping_order_num,shiping_order_goid);

            }
        });

    }

    public class ShowOrderTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            if (refresh == 0) {
//                mSwipeLayout.setRefreshing(true);
                mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
                mProgressDialog.setCancelable(true);
                mProgressDialog.setCanceledOnTouchOutside(false);

            } else if (refresh == 1) {
                mSwipeLayout.setRefreshing(true);
            }
        }

        protected String doInBackground(String... params) {
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userInfo", userInfo);
            map.put("row",params[0]);
            map.put("page",params[1]);
            map.put("driver_name",params[2]);
            map.put("driver_phone",params[3]);
            map.put("driver_suppliers",params[4]);
            map.put("driver_address",params[5]);
            map.put("shiping_order_num", params[6]);
            map.put("shiping_order_goid",params[7]);

            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appGetShipperToCar"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            if (refresh == 0) {
//                mSwipeLayout.setRefreshing(false);
                mProgressDialog.dismiss();

            } else if (refresh == 1) {
                mSwipeLayout.setRefreshing(false);
            }
            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {
                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    driverInfo = JsonUtil.getPersons(successMsg, new TypeToken<ArrayList<DriverInfo>>() {
                    }.getType());
                   DriverAdapter driverAdapter = new DriverAdapter(mContext,driverInfo);
                    lv_driver.setAdapter(driverAdapter);
                }
                }

        }
    }

    public class FPOrderTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {
            Map<String, String> map = new HashMap<>();
            map.put("driverId",driver_id);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appDriverISHaveGps"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {

            mProgressDialog.dismiss();

            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {
                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                        if (successMsg.equals("1")){
                            Intent mIntetn = new Intent();
                            mIntetn.putExtra("driver_id", driver_id);
                            mIntetn.putExtra("username", username);
                            mIntetn.setClass(mContext, EquipmentActivity.class);
                            startActivityForResult(mIntetn, 3);
                        }else {
                            String equipment_number = "";
                            Intent mIntetn = new Intent();
                            mIntetn.putExtra("fpstste", "0");
                            mIntetn.putExtra("driver_id", driver_id);
                            mIntetn.putExtra("equipment_number", equipment_number);
                            mIntetn.putExtra("username", username);
                            mIntetn.setClass(mContext, Main2Activity.class);
                            startActivityForResult(mIntetn, 3);
                        }
                }
            }

        }
    }

    class mOnItemClick implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              driver_id = driverInfo.get(position).getDriver_id();
            username = driverInfo.get(position).getUserName();
            driverName = driverInfo.get(position).getDriver_name();
            if (type.equals("1")){
                Intent mIntetn1 = new Intent();
                mIntetn1.setClass(mContext, QscxOrderActivity.class);
                mIntetn1.putExtra("driver_id", driver_id);
                startActivityForResult(mIntetn1, 1);

            }else if (type.equals("3")){

                Intent mIntetn = new Intent();
                mIntetn.setClass(mContext, BackFPActivity.class);
                mIntetn.putExtra("driver_id", driver_id);
                mIntetn.putExtra("driverName", driverName);
                startActivityForResult(mIntetn, 1);
//                PopupMenu popupMenu = new PopupMenu(mContext, view);
//                // menu布局
//                popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
//                // menu的item点击事件
//                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
//                    @Override
//                    public boolean onMenuItemClick(MenuItem item) {
//                        switch (item.getItemId()) {
//                            case R.id.item_fpOrder:
//                                Intent mIntetn = new Intent();
//                                mIntetn.setClass(mContext, BackFPActivity.class);
//                                mIntetn.putExtra("driver_id", driver_id);
//                                mIntetn.putExtra("driverName", driverName);
//                                startActivityForResult(mIntetn, 1);
//                                break;
//                            case R.id.item_ckOrder:
//                                Intent mIntent = new Intent();
//                                mIntent.putExtra("fpstste", "2");
//                                mIntent.setClass(mContext, BackOrderListActivity.class);
//                                startActivityForResult(mIntent, 1);
//                                break;
//                            default:
//                                break;
//                        }
////                    Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
//                        return false;
//                    }
//                });
//                // PopupMenu关闭事件
//                popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
//                    @Override
//                    public void onDismiss(PopupMenu menu) {
////                    Toast.makeText(getApplicationContext(), "关闭PopupMenu", Toast.LENGTH_SHORT).show();
//                    }
//                });
//                popupMenu.show();
//

            }else{
                PopupMenu popupMenu = new PopupMenu(mContext, view);
                // menu布局
                popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
                // menu的item点击事件
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.item_fpOrder:
                                FPOrderTask showOrderTask = new FPOrderTask();
                                showOrderTask.execute();
                                break;
                            case R.id.item_ckOrder:
                                Intent mIntetn1 = new Intent();
                                mIntetn1.setClass(mContext, SelectDriverOrderActivity.class);
                                mIntetn1.putExtra("driver_id", driver_id);
                                startActivityForResult(mIntetn1, 1);
                                break;
                            default:
                                break;
                        }
//                    Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
                        return false;
                    }
                });
                // PopupMenu关闭事件
                popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
                    @Override
                    public void onDismiss(PopupMenu menu) {
//                    Toast.makeText(getApplicationContext(), "关闭PopupMenu", Toast.LENGTH_SHORT).show();
                    }
                });
                popupMenu.show();

            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu_home; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_vehicle, menu);
        getMenuInflater().inflate(R.menu.menu_select, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item_select:
                Intent myIntetn = new Intent();
                myIntetn.putExtra("fpstste","1");
                myIntetn.setClass(mContext, DriverTjSelectActivity.class);
                startActivityForResult(myIntetn, 2);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 2) {
            refresh = 0;
            String driver_name1 = (String) data.getExtras().get("driver_name1");
            String driver_phone1 = (String) data.getExtras().get("driver_phone1");
            String driver_suppliers1 = (String) data.getExtras().get("driver_suppliers1");
            String driver_address1 = (String) data.getExtras().get("driver_address1");
            String shiping_order_num = (String) data.getExtras().get("shiping_order_num");
            String shiping_order_goid = (String) data.getExtras().get("shiping_order_goid");

            ShowOrderTask showOrderTask = new ShowOrderTask();
            showOrderTask.execute(row,page,driver_name1,driver_phone1,driver_suppliers1,driver_address1,shiping_order_num,shiping_order_goid);

        }

    }
    /**
     * Created by Wangzhiqiang on 2015/11/19.
     * button的点击方法
     */
    class mOnClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {

                default:
                    Intent mIntent2 = new Intent();
                    //把返回数据存入Intent
                    mIntent2.putExtra("result", 1);
                    //设置返回数据
                    setResult(3, mIntent2);
                    finish();
                    break;
            }
        }
    }

}